package ch.cryptobox.encryption;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {
	//private byte[] key;
	private SecretKeySpec skeySpec;
	private final Cipher cipher;

	public void regenerateKey(final int id)
	{
		try {
			SecretKeySpec k=KeyManager.getInstance().getKeyForNow(id);
			
			if(k!=null)
			{
				skeySpec=k;
				System.out.println("[AES] Already saved key");
				return;
			}
			
			final KeyGenerator kgen = KeyGenerator.getInstance("AES");

			kgen.init(128); // 192 and 256 bits may not be available


			final SecretKey skey = kgen.generateKey();
			final byte[] key = skey.getEncoded();

			skeySpec = new SecretKeySpec(key, "AES");
			KeyManager.getInstance().storeKey(skeySpec, id);
		} catch (final NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	}

	public byte[] encrypt(final byte[] data) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException
	{
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);	

		return cipher.doFinal(data);
	}
//
//	public byte[] decrypt(final byte[] data) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException
//	{
//		return decrypt(data,skeySpec);
//	}

	public byte[] decrypt(final byte[] data, final Date date, final int id) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException
	{
		final SecretKeySpec key=KeyManager.getInstance().getKey(date,id);
		if(key==null) return null;
		return decrypt(data,key);
	}

	public byte[] decrypt(final byte[] data, final SecretKeySpec key) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException
	{
		cipher.init(Cipher.DECRYPT_MODE, key);

		return cipher.doFinal(data);
	}

	public AES() throws NoSuchAlgorithmException, NoSuchPaddingException
	{
		cipher = Cipher.getInstance("AES");
	}
}